package com.zues.thread.design_mode.alternating_execute;

import com.zues.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock 演示交替执行Demo
 * 期望效果：三个线程，轮流打印a、b、c，打印5次
 * 线程1：a
 * 线程2：b
 * 线程3：c
 * 打印效果 ：abcabcabcabcabc
 */
@Slf4j(topic = "c.AlternatingExecuteDemo2")
public class Demo2 {

    public static void main(String[] args) {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();

        new Thread(() -> {
            awaitSignal.print("a", a, b);
        },"t1").start();
        new Thread(() -> {
            awaitSignal.print("b", b, c);
        },"t2").start();
        new Thread(() -> {
            awaitSignal.print("c", c, a);
        },"t3").start();

        ThreadUtil.sleep(1);

        awaitSignal.lock();
        try {
            a.signal();
        } finally {
            awaitSignal.unlock();
        }

    }
}


class AwaitSignal extends ReentrantLock {

    private int loopNumber;

    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void print(String str, Condition current, Condition next) {

        for (int i = 0; i < loopNumber; i++) {
            lock();
            try {
                try {
                    current.await();
                    System.out.print(str);
                    next.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                unlock();
            }
        }
    }


}